package com.hqc.gallery.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hqc.gallery.common.entities.User;

public class UserInSession implements Filter{
	
	private static final String SECURE_CONTEXT = "auth";

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		if (request instanceof HttpServletRequest) {
			HttpServletRequest req = (HttpServletRequest) request;
			User user = (User)req.getSession().getAttribute(User.BIND_NANE);
			if (user != null) {
				chain.doFilter(request, response);
				return;
			}
			if (req.getRemoteUser() != null) {
				user = new User();
				user.setUserId(req.getUserPrincipal().getName());
				user.setRole("admin");
				req.getSession().setAttribute(User.BIND_NANE, user);
			}
			if (SECURE_CONTEXT.equals(req.getContextPath())) {
				((HttpServletResponse)response).sendRedirect("/login.action");
				return;
			}
		}
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
